package com.hzeport.bgs22emduty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.dto.ParamVo;
import com.hzeport.bgs22emduty.entity.*;
import com.hzeport.bgs22emduty.enums.DeleteFlagEnum;
import com.hzeport.bgs22emduty.enums.STypeEnum;
import com.hzeport.bgs22emduty.enums.SeTypeEnum;
import com.hzeport.bgs22emduty.outbound.*;
import com.hzeport.bgs22emduty.outbound.db.ParamGroupDutyRepositoryImpl;
import com.hzeport.bgs22emduty.service.ParamGroupDutyService;
import com.hzeport.bgs22emduty.util.GuavacacheUtils;
import com.hzeport.bgs22emduty.vo.base.PageVO;
import com.hzeport.bgs22emduty.vo.paramgroupduty.ParamGroupDutyDto;
import com.hzeport.bgs22emduty.vo.paramgroupduty.ParamGroupDutyListVo;
import com.hzeport.bgs22emduty.vo.paramgroupduty.ParamGroupVo;
import com.hzeport.bgs22emduty.common.base.BaseResult;
import com.hzeport.bgs22emduty.common.base.BaseServiceImpl;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @author hzeport
 */

@Service
@Slf4j
@Setter( onMethod_ = @Resource )
public class ParamGroupDutyServiceImpl extends BaseServiceImpl< ParamGroupDutyRepositoryImpl, ParamGroupDuty > implements ParamGroupDutyService {

    private ParamGroupDutyRepository paramGroupDutyRepository;

    private BaseGroupInfoRepository baseGroupInfoRepository;

    private ParamDictionaryRepository paramDictionaryRepository;

    private BaseGroupUserRelationRepository baseGroupUserRelationRepository;

    private BasePersonInfoRepository basePersonInfoRepository;

    private DutyScheduleGroupRecordRepository dutyScheduleGroupRecordRepository;

    private GuavacacheUtils guavacacheUtils;

    @Override
    public BaseResult< Page< ParamGroupDutyListVo > > getPage( PageVO pageVO , UserInfoDetailVO userInfoDetailVO ) {



        Page< ParamGroupDuty > page = paramGroupDutyRepository.getGroupPage( pageVO , userInfoDetailVO );

        List< ParamGroupDutyListVo > voList = new ArrayList<>();
        for ( ParamGroupDuty groupDuty : page.getRecords() ) {
            ParamGroupDutyListVo vo = new ParamGroupDutyListVo();

            BeanUtils.copyProperties( groupDuty , vo );
            vo.setSeTypeName( SeTypeEnum.getDescByCode( groupDuty.getSeType() ) );
            vo.setSTypeName( paramDictionaryRepository.getOne( new LambdaQueryWrapper<ParamDictionary>()
                .eq( ParamDictionary::getParamModule , "SETDT" )
                .eq( ParamDictionary::getParamCode , groupDuty.getSType() ) , false ).getParamName()
            );


            List<ParamGroupVo> paramGroupVos = new ArrayList<>();
            List<BaseGroupInfo> baseGroupInfos2 = baseGroupInfoRepository.list( new LambdaQueryWrapper<BaseGroupInfo>()
                    .in( BaseGroupInfo::getGroupGuid , Arrays.asList( groupDuty.getGroupId().split( "," ) ) )
                    .orderByAsc( BaseGroupInfo::getSort )
            );
            Map<String, BaseGroupInfo> baseDeptInfoMap = baseGroupInfos2.stream().collect(Collectors.toMap(i -> i.getGroupGuid(), i -> i));
            List<ParamGroupDuty> baseGroupInfos = paramGroupDutyRepository.list(new LambdaQueryWrapper<ParamGroupDuty>()
                    .eq(ParamGroupDuty::getCustomId, userInfoDetailVO.getCustomscode())
                            .eq(ParamGroupDuty::getSType,groupDuty.getSType())
                    .in(ParamGroupDuty::getGroupId,Arrays.asList( groupDuty.getGroupId().split( "," ) ) ))
                    ;

            for ( ParamGroupDuty baseGroupInfo : baseGroupInfos ) {
                ParamGroupVo groupVo = new ParamGroupVo();
                groupVo.setId( baseGroupInfo.getGroupId() );
                BaseGroupInfo baseGroupInfo1 = baseDeptInfoMap.get(baseGroupInfo.getGroupId());
                if (!ObjectUtils.isEmpty(baseGroupInfo1)){
                    groupVo.setDisplayName( baseGroupInfo1.getGroupName() );
                }
                paramGroupVos.add( groupVo );
            }
            vo.setGroupVoList( paramGroupVos );
            voList.add( vo );
        }

        Page< ParamGroupDutyListVo > voPage = new Page<>();
        voPage.setTotal( page.getTotal() );
        voPage.setRecords( voList );

        return BaseResult.ok( voPage );
    }

    @Override
    public BaseResult< String > saveData( ParamGroupDutyDto dto , UserInfoDetailVO userInfoDetailVO ) {


        List< ParamGroupDuty > insertGroupDuty = new ArrayList<>();
        for ( String groupId : dto.getGroupVoList() ) {
            ParamGroupDuty duty = paramGroupDutyRepository.getOne( new LambdaQueryWrapper< ParamGroupDuty >()
                    .eq( ParamGroupDuty::getSeType , dto.getSeType() )
                    .eq( ParamGroupDuty::getSType , dto.getSType() )
                    .eq( ParamGroupDuty::getCustomId , userInfoDetailVO.getCustomscode() )  , false );
            if( ! ObjectUtils.isEmpty( duty ) ){
                BaseGroupInfo groupInfo = baseGroupInfoRepository.getOne( new LambdaQueryWrapper< BaseGroupInfo >()
                        .eq( BaseGroupInfo::getGroupGuid , groupId ) );
                return BaseResult.failed( "该日程已配置群组，请删除后重新设置" );
            }
            ParamGroupDuty groupDuty = new ParamGroupDuty();
            groupDuty.setCustomId( userInfoDetailVO.getCustomscode() );
            groupDuty.setSeType( dto.getSeType() );
            groupDuty.setSType( dto.getSType() );
            groupDuty.setGroupId( groupId );
            groupDuty.setDelFlag( DeleteFlagEnum.NOT_DELETE.getValue() );
            groupDuty.setCreateBy( userInfoDetailVO.getUserId() );
            groupDuty.setUpdateBy( userInfoDetailVO.getUserId() );
            insertGroupDuty.add( groupDuty );
        }
        paramGroupDutyRepository.saveBatch( insertGroupDuty );
        guavacacheUtils.claerParamGroup();
        return BaseResult.ok( null ,"添加成功" );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult< String > delete( ParamGroupDutyDto dto , UserInfoDetailVO userInfoDetailVO ) {
        List<ParamGroupDuty> paramGroupDuties=paramGroupDutyRepository.list( new LambdaQueryWrapper<ParamGroupDuty>()
                .eq( ParamGroupDuty::getSeType , dto.getSeType() )
                .eq( ParamGroupDuty::getSType , dto.getSType() )
                .eq(ParamGroupDuty::getCustomId,userInfoDetailVO.getCustomscode())
        );
        paramGroupDutyRepository.remove( new LambdaQueryWrapper<ParamGroupDuty>()
                .eq( ParamGroupDuty::getSeType , dto.getSeType() )
                .eq( ParamGroupDuty::getSType , dto.getSType() )
                .eq(ParamGroupDuty::getCustomId,userInfoDetailVO.getCustomscode())
        );
        dutyScheduleGroupRecordRepository.remove(new LambdaQueryWrapper<DutyScheduleGroupRecord>()
                .eq( DutyScheduleGroupRecord::getSeType , dto.getSeType() )
                .eq( DutyScheduleGroupRecord::getDutyType , dto.getSType() )
                .eq(DutyScheduleGroupRecord::getCustomId,userInfoDetailVO.getCustomscode()));
        return BaseResult.ok( null ,"删除成功" );
    }

    @Override
    public BaseResult< List< ParamVo > > getGroupList( UserInfoDetailVO userInfoDetailVO ) {
        try {
            List<BaseGroupInfo> groupInfoList = baseGroupInfoRepository.list(new LambdaQueryWrapper<BaseGroupInfo>()
                    .eq(BaseGroupInfo::getCustomId, userInfoDetailVO.getCustomscode()));
            List<ParamVo> paramVos = groupInfoList.stream().map(it -> {
                ParamVo paramVo = new ParamVo();
                paramVo.setParamCode(it.getGroupGuid());
                paramVo.setParamName(it.getGroupName());
                return paramVo;
            }).collect(Collectors.toList());
            return BaseResult.ok(paramVos);
        }
        catch (Exception ex)
        {
            log.error("获取群组列表失败:"+ex.getMessage());
            return BaseResult.failed("系统错误");
        }
    }

    @Override
    public BaseResult< List< ParamVo > > getGroupUser( String groupId ) {
        List< BaseGroupUserRelation > groupUserRelations = baseGroupUserRelationRepository.list( new LambdaQueryWrapper<BaseGroupUserRelation>()
            .eq( BaseGroupUserRelation::getGroupId , groupId )
        );
        if ( CollectionUtils.isEmpty( groupUserRelations ) ) {
            return BaseResult.ok();
        }
        List< String > userNos = groupUserRelations.stream().map( BaseGroupUserRelation::getUserId ).collect( Collectors.toList() );
        List<BasePersonInfo> basePersonInfos = basePersonInfoRepository.list( new LambdaQueryWrapper<BasePersonInfo>()
                .in( BasePersonInfo::getUserno  , userNos ).orderByDesc( BasePersonInfo::getGlobalSort )
        );

        List<ParamVo> paramVos = basePersonInfos.stream().map(it -> {
            ParamVo paramVo = new ParamVo();
            paramVo.setParamCode( it.getUserno() );
            paramVo.setParamName( it.getUsername() );
            return paramVo;
        }).collect(Collectors.toList());
        return BaseResult.ok(paramVos);
    }
}
